package com.taomeishu.mailcrazy.checkers.sohu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.taomeishu.mailcrazy.CheckResult;
import com.taomeishu.mailcrazy.Mail;
import com.taomeishu.mailcrazy.http.ClientResponse;
import com.taomeishu.mailcrazy.parser.ResultParseException;
import com.taomeishu.mailcrazy.parser.ResultParser;

public class SohuResultParser implements ResultParser {

	@Override
	public CheckResult parse(ClientResponse clientResponse, String username, String domainName) throws ResultParseException {
		String s = new String(clientResponse.getData());
		CheckResult result = new CheckResult(true);
		Mail mail = new Mail(username, domainName);
		result.setMail(mail);
		try {
			JSONObject json = new JSONObject(s);
			int status = json.getInt("status");
			if (1 == status) {
				// exist
				result.addExistMail(mail);
				JSONArray jsonArray = json.getJSONArray("sugestnames");
				for (int i = 0, len = jsonArray.length(); i < len; ++i) {
					String notExistName = jsonArray.getString(i);
					result.addNotExistMail(new Mail(notExistName, domainName));
				}
			} else if (0 == status) {
				result.addNotExistMail(mail);
			}
		} catch (JSONException e) {
			throw new ResultParseException(e);
		}
		return result;
	}
}
